import  torch
import  pandas as pd
import  numpy as np
import  matplotlib.pyplot as plt

plt.rcParams['font.family'] = ['Microsoft YaHei']
plt.rcParams['font.sans-serif'] = ['SimHei']
data=pd.read_csv("Income1.csv")
print(data)
X=torch.from_numpy(data.Education.values.reshape(-1,1).astype(np.float32))
Y=torch.from_numpy(data.Income.values.reshape(-1,1).astype(np.float32))

'''分解写法'''
w=torch.rand(1,requires_grad=True)
b=torch.zeros(1,requires_grad=True)

'''模型公式：w@x+b'''
learning_rate=0.0001

for epoch in range(5000):
    for x,y in zip(X,Y):
        y_pred=torch.matmul(x,w)+b
        loss=(y-y_pred).pow(2).mean()
        if not w.grad is None:
            w.grad.data.zero_()
        if not b.grad is None:
            b.grad.data.zero_()
        loss.backward()
        with torch.no_grad():
            '''沿着梯度方向下降,learning_rate避免剧烈震荡'''
            w.data-=w.grad.data*learning_rate
            b.data-=b.grad.data*learning_rate

plt.scatter(data.Education,data.Income)
plt.plot(X.numpy(),(X*w+b).data.numpy(),c='r')
plt.title("线性回归分解写法")
plt.xlabel("教育")
plt.ylabel("收入")
plt.show()
